#include "Disc.h"
#include "../SGD Wrappers/SGD_GraphicsManager.h"
#include "DestroyEntityMessage.h"
#include "GamePlayState.h"
#include <sstream>
#include "Player.h"
#include "Enemy.h"
#include "Game.h"
#include "../SGD Wrappers/SGD_Event.h"

Disc::Disc(std::string en)
{
	emitter = en;
	activeemitter = ParticleManager::GetInstance()->CreateEmitter(emitter, this);
}


Disc::~Disc()
{
	if (activeemitter)
		ParticleManager::GetInstance()->FreeEmitter(activeemitter);
}

void Disc::Update(float elapsedTime)
{
	Enemy* owner = dynamic_cast<Enemy*>(GetOwner());
	if (dynamic_cast<Player*>(owner->GetPlayer())->GetDestinationPlanet())
	{
		SGD::Vector hook = owner->GetHookPos() - owner->GetPlayer()->GetRect().ComputeCenter();
		float len = hook.ComputeLength();
		hook.Normalize();
		SGD::Point line = owner->GetPlayer()->GetRect().ComputeCenter();
		SGD::Point minus = { GetRect().ComputeCenter().x - GetRadius(), GetRect().ComputeCenter().y - GetRadius() };
		SGD::Point plus = { GetRect().ComputeCenter().x + GetRadius(), GetRect().ComputeCenter().y + GetRadius() };
		for (float i = 0; i < len; i++)
		{
			line += hook;
			if ((minus.x <= line.x) && (minus.y <= line.y) && (plus.x >= line.x) && (plus.y >= line.y))
			{
				SGD::Event ev = { "GRAPPLEDETACH" };
				ev.SendEventNow(nullptr);
				dynamic_cast<Player*>(owner->GetPlayer())->SetDestinationPlanet(nullptr);
				DestroyEntityMessage* msg = new DestroyEntityMessage(this);
				msg->QueueMessage();
				msg = nullptr;
				return;
			}
		}
	}
	Projectiles::Update(elapsedTime);
}

void Disc::Render(void)
{
	SGD::Rectangle camOffset{ { Game::GetInstance()->GetCameraPos().x - 100,
		Game::GetInstance()->GetCameraPos().y - 100 },
		SGD::Size{ (Game::GetInstance()->GetScreenWidth() + 500) / Game::GetInstance()->GetZoomLevel(),
		(Game::GetInstance()->GetScreenHeight() + 500) / Game::GetInstance()->GetZoomLevel() } };
	SGD::Rectangle posRect = { this->GetRect().ComputeCenter(), SGD::Size{ 1, 1 } };
	if (camOffset.IsIntersecting(posRect))
	{
		SGD::Rectangle rect =
		{ SGD::Point{ position.x - Game::GetInstance()->GetCameraPos().x,
		position.y - Game::GetInstance()->GetCameraPos().y }, size };
		SGD::GraphicsManager::GetInstance()->DrawRectangle(
			rect, SGD::Color{ 127, 127, 80 });
	}
}

void Disc::HandleCollision(const IEntity* other)
{
	if (GetOwner() != other && (other->GetType() != ENT_PLANET))
	{
		ParticleManager::GetInstance()->FreeEmitter(activeemitter);
		DestroyEntityMessage* msg = new DestroyEntityMessage(this);
		msg->QueueMessage();
		msg = nullptr;
	}
}